package org.luosl.webmagicx.cli

import org.apache.commons.cli.{CommandLine, DefaultParser, Options}

/**
  * 命令行属性类
  * @param confPath confPath
  * @param port port
  */
case class CliProp(confPath:Option[String], host:Option[String], port:Option[Int])

/**
  * Created by luosl on 2017/12/15.
  */
class Cli(args:String*) {

  private val options:Options = new Options()
      .addOption("h", true, "host")
      .addOption("c", true, "爬虫配置文件/目录路径")
      .addOption("p", true, "http监听端口")

  private val cli: CommandLine = {
    val p:DefaultParser = new DefaultParser()
    p.parse(options,args.toArray)
  }

  def optionVal(key:String):String = {
    if(cli.hasOption(key)){
      cli.getOptionValue(key)
    }else{
      throw new NoSuchElementException(s"无效的key:$key")
    }
  }

  def optionValOpt(key:String):Option[String] = {
    if(cli.hasOption(key)){
      Option(cli.getOptionValue(key))
    }else{
      Option.empty[String]
    }
  }

  def cliProp():CliProp = {
    CliProp(optionValOpt("c"),optionValOpt("h"),optionValOpt("p").map(_.toInt))
  }

}

object Cli{
  def apply(args: String*): Cli = new Cli(args:_*)
}
